package top.carrotguo.weibo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtils {

    /**
     * 保存图片
     * @param context
     * @param image
     * @param fileName
     */
    public static void saveImage(Context context, Bitmap image, String fileName){
        //获取sd卡状态
        String storage = Environment.getExternalStorageState();
        if (!storage.equals(Environment.MEDIA_MOUNTED)) {
            ToastUtils.shortToast(context,"无法保存，请检测sd卡状态");
            return;
        }
        //获取sd卡路径
        File storageDirectory = Environment.getExternalStorageDirectory();
        //获取图片保存路径
        File file = new File(storageDirectory,File.pathSeparator+"weibodemo"+File.pathSeparator+"image");
        //判断文件夹是否存在，不存在需创建
        if (!file.exists()) {
            file.mkdirs();
        }
        File saveFile = new File(file,fileName);
        //查看文件是否存在，不存在则创建文件
        if (!saveFile.exists()) {
            try {
                saveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedOutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(saveFile));
            image.compress(Bitmap.CompressFormat.PNG,100,outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(outputStream);
        }
    }
}
